<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/14
 * Time: 14:41
 * Created by Created by Panxsoft.
 */

namespace App\Models\Products;

use App\Models\IndexConfig\ProductDescriptionIndexConfigurator;
use App\Models\Concerns\ScopeFilterable;

use App\Services\MobileApp\AppEnv;
use Illuminate\Database\Eloquent\Model;
use ScoutElastic\Searchable;

/**
 * Class ProductDescription - 产品描述（对应不同语言）
 *
 * @property string name - 标题
 * @property string meta_title - 网页 meta 标签标题
 *
 * @package App\Models\Products
 */
class ProductDescription extends Model
{
    /**
     * $indexConfigurator / $searchRules / $mapping 为使用 ScoutElastic 必须的参数
     */
    use Searchable;
    protected $indexConfigurator = ProductDescriptionIndexConfigurator::class;
    protected $searchRules = [];
    protected $mapping = [
        'properties' => [
            'description' => [
                'type' => 'text',
                'fields' => [
                    'raw' => [
                        'type' => 'keyword',
                    ]
                ]
            ],
            'name' => [
                'type' => 'text',
                'fields' => [
                    'raw' => [
                        'type' => 'keyword',
                    ]
                ]
            ],
        ]
    ];

    use ScopeFilterable;

    protected $guarded = [];
    protected $table = 'product_description';
    protected $primaryKey = 'product_id';

    /**
     * 防止详情中的图片尺寸过大，撑开 webview
     */
    const ADJUST_HTML = '<meta name="viewport" content="width=device-width,initial-scale=1"><style>img {width: 100% !important;}</style>';

    /**
     * @return null|string
     */
    public function getDescriptionAttribute()
    {
        $description = $this->attributes['description'];

        if ($description) {
            return self::ADJUST_HTML .
                // ENT_QUOTES 表示把 &#039; 转成 '
                html_entity_decode($description, ENT_QUOTES, 'UTF-8');
        } else {
            return null;
        }
    }

    /**
     * @param string $keyword
     *
     * @return array|null
     */
    static public function trySearchProductIds(string $keyword)
    {
        try {
            return self::elasticSearchProductIdsByKeyword($keyword);
        } catch (\Exception $exception) {
            return self::getProductIdsByKeyword($keyword);
        }
    }

    /**
     * @param string $keyword
     *
     * @return array
     */
    static public function elasticSearchProductIdsByKeyword(string $keyword): array
    {
        return ProductDescription::search($keyword)
            ->where('language_id', AppEnv::languageId())
            ->get()
            ->pluck('product_id')
            ->all();
    }

    /**
     * @param string $keyword
     *
     * @return array
     */
    static public function getProductIdsByKeyword(string $keyword): array
    {
        return (new self)
            ->where('language_id', AppEnv::languageId())
            ->columnsKeywordOrLike(['name', 'meta_title', 'meta_description', 'meta_keyword'], $keyword)
            ->pluck('product_id')
            ->all();
    }
}